<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>魔法理论json数据文件直接汉化工具</title>
</head>
<body>
<div>上传需处理的json文件<input type="file" id="json_en"></div>
<div>上传汉化文本（含有cnItems对象的js文件）<input type="file" id="text_cn"></div>
<button onclick="onBtnClick()">开始处理</button>

<script>
    let trans_key = [
    	"name",
    	"actname",
    	"actdesc",
    	"desc",
        "verb",
        "flavor",
    ];

    var cnText = {};

    function replace_item(item) {
	    trans_key.forEach(key => {
		    if (item[key]) {
			    if (item[key] && cnText[item[key]] && typeof cnText[item[key]] === "string") {
				    item[key] = cnText[item[key]];
				    return;
			    }

			    let text_lower = item[key].toLowerCase();
			    if (cnText[text_lower] && typeof cnText[text_lower] === "string") {
				    item[key] = cnText[text_lower];
			    }
		    }
	    });
    }

    function replace_items(data_array) {
	    if ( Array.isArray(data_array)) {
		    data_array.forEach(item => {
			    if (!item.name) {
				    item.name = item.id
			    }

			    replace_item(item);

			    if (item.log) {
				    replace_item(item.log);
                }
		    });
	    }
    }

    function onBtnClick() {
        let file_json_en = document.getElementById("json_en").files[0];
        let file_text_cn = document.getElementById("text_cn").files[0];
        file_json_en.text().then(text_json_en =>{
        	file_text_cn.text().then(text_cn =>{
        		eval(text_cn);
        		cnText = cnItems;
        		for (let cnItem in cnText) {
        			if (!cnText[cnItem.toLowerCase()])
			        cnText[cnItem.toLowerCase()] = cnText[cnItem]
                }
        		let json_data = JSON.parse(text_json_en);
        		if (Array.isArray(json_data)) {
			        replace_items(json_data);
                } else {
			        for (let k in json_data.data) {
				        replace_items(json_data.data[k])
                    }
                }


                let text_json_cn = JSON.stringify(json_data, null, 8);
		        text_json_cn = text_json_cn.replaceAll(" ".repeat(8), "\t");
                let blob_json = new Blob([text_json_cn]);
		        let download_url =  URL.createObjectURL(blob_json);

                let download_ele = document.createElement("a");
		        download_ele.href = download_url;
		        download_ele.download = file_json_en.name;
		        download_ele.click();
            })
        })
    }

</script>
</body>
</html>